import { Action, Lib, Seed } from "../types";
import uaa from "../uaa";

export class LibManager {
  private cache: Record<string, Lib> = {}

  public init() {
    const modules: Record<string, any> = import.meta.glob('/src/seed-application/libs/*/index.ts', { eager: true });
    for(const path in modules) {
      const libName = path.substring('/src/seed-application/libs/'.length, path.length - '/index.ts'.length)
      this.cache[libName] = modules[path]['default']
    }
    console.log('seed-libs', this.cache)
  }
  
  public getLib(libName: string) {
    const lib = this.cache[libName]
    if(!lib) throw Error(`库【${libName}】不存在`)

    return lib
  }

  public getLibs(...libNames: string[]) {
    const ret: Record<string, Lib> = {}
    for(const libName of libNames) ret[libName] = this.getLib(libName)

    return ret
  }

  public getLibSeeds(libNames: string[], containUaa?: boolean) {
    const ret: Record<string, Seed> = {}
    if(!libNames) return ret
  
    for(const libName of libNames) {
      const lib = this.cache[libName]
      if(!lib) throw Error(`库【${libName}】不存在`)
        
      const libSeeds = lib.seeds
      for(const seedName in libSeeds) ret[seedName] = libSeeds[seedName]
    }

    if(containUaa) for(const seedName in uaa.seeds) ret[seedName] = uaa.seeds[seedName]
  
    return ret
  }

  public getLibActions(libNames: string[]) {
    const ret: Record<string, Action> = {}
    if(!libNames) return ret
    
    for(const libName of libNames) {
      const lib = this.getLib(libName)
      const actions = lib.actions
      if(!actions) continue
      
      for(const actionName in actions) {
        if(ret[actionName]) throw Error(`库【${libName}】里的行为【${actionName}】和其它库里的行为重复`)

        ret[actionName] = actions[actionName]
      }
    }

    return ret
  }
}